#include <sstream>

#include "SSLWrapper.hpp"
#include "ConnectSocket.hpp"
#include "Logger.hpp"

int protected_main(int argc, char **argv) {
	if ((argc != 4) && (argc != 6)) {
		std::cerr << "Syntax:" << std::endl;
		std::cerr << argv[0] << " <Host> <Port> <noverify|CA-Zertifikat> (<Client-Zertifikat> <Client Key>)" << std::endl;
		exit(1);
	}
	
	//initialize SSL
	SSL_CTX* globalContext = SSLWrapper::init();

	//configure it
	if (strcmp("noverify", argv[3]) != 0) {
		SSLWrapper::loadHierarchy(globalContext, std::string(argv[3]));
		SSLWrapper::setVerifyMode(globalContext, SSL_VERIFY_PEER);
	}
	
	if (argc > 4) {
		SSLWrapper::loadCertificate(globalContext, std::string(argv[4]));
		SSLWrapper::loadPrivatekey(globalContext, std::string(argv[5]));
	}
	
	ConnectSocket* socket = new ConnectSocket(argv[1], atoi(argv[2]));
	TCPConnection connection = socket->connect();
	
	SSL* ssl = SSLWrapper::newConnection(globalContext);
	BIO* bio = SSLWrapper::sessionToChannel(connection.getFD(), ssl, true);
	
	LOGSTRM(Logger::INFO, "Peer Certificate: " << SSLWrapper::sslPeerCertificateToString(ssl));
	
	SSLWrapper::writeLineToChannel(bio, "GET / HTTP/1.0\r\n");
	SSLWrapper::writeLineToChannel(bio, "\r\n");
	
	std::string line;
	do {
		line = SSLWrapper::readLineFromChannel(bio);
		std::cout << line;
	} while (line.length() != 0);
	
	SSLWrapper::closeSession(ssl);

	connection.close();

	return 0;
}

int main(int argc, char** argv) {

	try {
		return protected_main(argc, argv);
	} catch (const GenericException& e) {
		e.terminate();
	}
	return 1;
}
